package com.example.partner.activity.home;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.partner.activity.MainActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.User;
import com.example.partner.model.request.UserLoginRequest;

import androidx.appcompat.app.AppCompatActivity;

import com.example.partner.R;
import com.example.partner.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class LoginActivity extends AppCompatActivity {
    final String TAG = "LoginActivity";

    // UI组件
    private EditText etUserAccount;
    private EditText etUserPassword;
    private Button btnLogin;
    private TextView tvRegisterLink;
    private UserService userService;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUserAccount = findViewById(R.id.etUserAccount);
        etUserPassword = findViewById(R.id.etUserPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegisterLink = findViewById(R.id.tvRegisterLink);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 更换为您的服务器URL
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        userService = retrofit.create(UserService.class);

        btnLogin.setOnClickListener(view -> loginUser());
        tvRegisterLink.setOnClickListener(v -> {
            // 启动注册页面的Activity
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void loginUser() {
        String userAccount = etUserAccount.getText().toString();
        String userPassword = etUserPassword.getText().toString();
        UserLoginRequest request = new UserLoginRequest();
        request.setUserAccount(userAccount);
        request.setUserPassword(userPassword);
        userService.userLogin(request).enqueue(new Callback<BaseResponse<User>>() {
            @Override
            public void onResponse(Call<BaseResponse<User>> call, Response<BaseResponse<User>> response) {
                BaseResponse<User> responseBody = response.body();
                User crruentUser = responseBody.data;
                if (responseBody != null){
                     if (response.isSuccessful()) {
                         Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                         // 处理成功的响应
                         Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                         SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
                         SharedPreferences.Editor myEdit = sharedPreferences.edit();
                         myEdit.putString("userAccount", crruentUser.getUserAccount());
                         myEdit.putLong("userId", crruentUser.getId());
                         myEdit.putString("username", crruentUser.getUsername());
                         myEdit.putString("tags", crruentUser.getTags());
                         myEdit.putString("profile", crruentUser.getProfile());
                         myEdit.putString("avatar", crruentUser.getAvatarUrl());
                         myEdit.putString("phone", crruentUser.getPhone());
                         myEdit.putString("email", crruentUser.getEmail());
                         myEdit.putInt("role", crruentUser.getUserRole());
                         myEdit.commit();
                         startActivity(intent);
                         // 基于responseBody进行进一步处理
                     } else {
                        // 处理错误情况
                 }
            }
            }

            @Override
            public void onFailure(Call<BaseResponse<User>> call, Throwable t) {
                // 网络错误处理
                Log.e(TAG, "post回调失败：" + t.getMessage() + "," + t.toString());
                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
